<template>
  <div class="panel">
    <left-menu :user-id="userId"></left-menu>
    <center-list :online-users="userList"></center-list>
    <right-content></right-content>
  </div>

</template>

<script>
import "@/css/imitateWechat/imitateWechat.css";
import {ElMessage} from "element-plus";
import LeftMenu from "../components/LeftMenu";
import RightContent from "../components/RightContent";
import CenterList from "../components/CenterList";
import store from "../../sysConfig/store.js";
import emitter from "../../sysConfig/bus.js"
export default {
  name: "iChatMain",
  components: {CenterList, RightContent, LeftMenu},
  data(){
    return{
      socket:null,
      userId:"",
      userList:[]
    }
  },
  mounted() {
    let curUser=sessionStorage.getItem("userId");
    store.setUserId(curUser);//记录当前登陆的账号
    this.userId=store.userId;

    this.openSocket();
    window.onbeforeunload=()=>{
      alert("浏览器即将关闭");
      this.closeSocket();
    }
    this.sendEvtImp();
  },
  beforeUnmount() {
    this.closeSocket();
    emitter.off("sendMsgEvt");
  },
  methods:{
    openSocket:function (){

      if(typeof(WebSocket) == "undefined") {
        console.log("您的浏览器不支持WebSocket");
      }else{
        console.log("您的浏览器支持WebSocket");
        //实现化WebSocket对象，指定要连接的服务器地址与端口  建立连接
        //等同于socket = new WebSocket("ws://localhost:8888/xxxx/im/25");
        //var socketUrl="${request.contextPath}/im/"+$("#userId").val();
        let curUrl= window.location.href;
        let urlArr=curUrl.split("\/");
        let socketUrl=urlArr.slice(0,3).join('//')+"/springboot/multiWebsocketApi/"+this.userId;//
        socketUrl= "http://192.168.0.110:8081/springboot/myHandler/"+this.userId;
        socketUrl=socketUrl.replace("https","ws").replace("http","ws");

        console.log(socketUrl);
        if(this.socket!=null){
          this.socket.close();
          this.socket=null;
        }
        this.socket = new WebSocket(socketUrl);
        //打开事件
        this.socket.onopen = function() {
          console.log("websocket已打开");
          //socket.send("这是来自客户端的消息" + location.href + new Date());
        };
        let _this=this;
        //获得消息事件
        this.socket.onmessage = function(msg) {
          console.log(msg.data);
          let msgObj=JSON.parse(msg.data);
          switch (msgObj["msgType"]){
            case "ConnectInfo":
              ElMessage({message:msgObj["msgBody"],type:"success",duration:1000})
              break;
            case "UserList":
              _this.userList=msgObj["onlineList"].filter(e=>e!==_this.userId);//msgObj["onlineList"];//
              //console.log(_this.userList);
              break;
            case "Message":
              store.addChatItem(msgObj);
              break;
          }
          _this.rcvMsg=msg.data;
          //发现消息进入    开始处理前端触发逻辑
        };
        //关闭事件
        this.socket.onclose = function() {
          console.log("websocket已关闭");
        };
        //发生了错误事件
        this.socket.onerror = function() {
          console.log("websocket发生了错误");
        }
      }
    },
    sendMessage:function (){
      if(typeof(WebSocket) == "undefined") {
        console.log("您的浏览器不支持WebSocket");
      }else {
        console.log("您的浏览器支持WebSocket");
        //console.log('{"toUserId":"'+$("#toUserId").val()+'","contentText":"'+$("#contentText").val()+'"}');
        this.socket.send(JSON.stringify({"fromUserId":this.userId,"toUserId":this.toUser,"contentText":this.msg}));
      }
    },
    sendEvtImp:function (){
      emitter.on("sendMsgEvt",(msg)=>{
        if(typeof(WebSocket) == "undefined") {
          console.log("您的浏览器不支持WebSocket");
        }else {
          //console.log("您的浏览器支持WebSocket");
          let msgObj={"srcUserId":this.userId,"destUserId":store.destUserId,"msgBody":msg,"msgType":"Message"};
          store.addChatItem(msgObj);
          this.socket.send(JSON.stringify(msgObj));
        }
      });
    },
    closeSocket:function (){
      if(this.socket!=null){
        this.socket.close();
        this.socket=null;
      }
    }
  }
}
</script>

<style scoped>

</style>